/**
 * Initialize your data structure here.
 * @author dingyue.zhf
 * @description 971. 翻转二叉树以匹配先序遍历 https://leetcode-cn.com/problems/flip-binary-tree-to-match-preorder-traversal/
 */
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 *
 * value互不相同
 *
 */
/**
 * @param {TreeNode} root
 * @param {number[]} voyage
 * @return {number[]}
 */
var flipMatchVoyage = function (root, voyage) {
  const ret = [];
  let idx = 0;
  /** 交换节点顺序 */
  const swap = (node) => {
    ret.push(node.val);
    let left = node.left;
    node.left = node.right;
    node.right = left;
  };
  const preOrder = (node) => {
    if (!node) {
      return true;
    }
    if (node.val !== voyage[idx]) {
      return false;
    }
    idx++;
    // 这里进递归会导致下标+1
    if (node.left && node.left.val !== voyage[idx]) {
      // 尝试翻转
      swap(node);
    }
    if (!preOrder(node.left)) {
      return false;
    }
    if (!preOrder(node.right)) {
      return false;
    }
    return true;
  };

  if (!preOrder(root)) {
    return [-1];
  }
  return ret;
};
